import React from "react";
import {ActivityIndicator, Alert, DeviceEventEmitter, InteractionManager, ScrollView, View} from "react-native";
import chjStyle from "../../../CustomStyle";
import ModuleCommonHeader from "../../module/ModuleCommonHeader";
import CarConfig from "./CarConfig";
import CommonTextItem from "../common/CommonTextItem";
import SingleSelectionTextItem from "../common/SingleSelectionTextItem";
import InputTextItem from "../common/InputTextItem";
import DateInputTextItem from "../common/DateInputTextItem";
import SwitchTextItem from "../common/SwitchTextItem";
import CarBrandSelection from "../common/CarBrandSelection";
import CarSeriesSelection from "../common/CarSeriesSelection";
import CarModelSelection from "../common/CarModelSelection";
import CommonMultiListSelection from "../common/CommonMultiListSelection";
import CommonListSelection from "../common/CommonListSelection";
import Util from "../../Util";
import NextButton from "../common/NextButton";
import {ActionConst, Actions} from "react-native-router-flux";
import {connect} from "react-redux";
const cityJson = require('../../../../configs/city.json');

class BaseInfo extends React.Component {
    // 构造函数，可执行初始化操作
    constructor(props) {
        super(props);
        // 在ES6，在构造函数里初始化state
        this.state = {
            isLoading: true,
            sourcelist: [],
            shopSourcelist: [],
            tradeType: '个人' // 成交类型，个人0，企业1
        };
        if (!Util.selectCar) {
            Util.selectCar = {};
        }
        if (!Util.selectCar.basicinfo) {
            Util.selectCar.basicinfo = Util.defaultBasicinfo();
        } else if (!Util.selectCar.basicinfo.areaid) {
            // 针对老数据做的修补
            Util.selectCar.basicinfo.areaid = {value: '', name: '商家所在地'};
        }
        this._enterCarSource = this._enterCarSource.bind(this);
        this._shopSourceSelected = this._shopSourceSelected.bind(this);
        this.onCarSourceSelected = this.onCarSourceSelected.bind(this);
    }

    // 组件被加载时
    componentDidMount() {

        // 在交互之后去读取本地存储
        InteractionManager.runAfterInteractions(() => {
            // Util.storage.remove({
            //     key:'carsource',
            //     id: '1000'
            // });

            // 读取本地，如果没有的话就请求网络
            Util.storage.load({
                key: 'shopsource',
                id: '1000'
            }).then(ret => {
                this.state.shopSourcelist = ret;
            }).catch(err => {
                this.requestShopSourceList();
            });

            // 读取本地，如果没有的话就请求网络
            Util.storage.load({
                key: 'carsource',
                id: '1000'
            }).then(ret => {
                this.setState({isLoading: false, sourcelist: ret});
            }).catch(err => {
                this.requestCarsourcelist();
            });
        });
    }

    componentWillUnmount() {
    }

    requestShopSourceList() {
        const user = Util.getUser();
        /// 请求车辆商家地区列表
        const params = {
            token: user.token,
            userid: user.id
        };
        Util.postServer('user/queryarealist', params, (result) => {
            this.state.shopSourcelist = result.data.arealist;
            Util.storage.save({
                key: 'shopsource',
                id: '1000',
                rawData: result.data.arealist
            });
        }, (msg) => {
            Alert.alert(msg);
        });
    }

    requestCarsourcelist() {
        const params = {
            type: null,
            userid: Util.getUser().id,
        };
        Util.postServer('user/carsourcelist', params, (result) => this.onRequestListSuccess(result), (msg) => this.onRequestListFailed(msg));
    }

    onRequestListSuccess(result) {
        Util.storage.save({
            key: 'carsource',
            id: '1000',
            rawData: result.data.sourcelist
        });
        this.setState({isLoading: false, sourcelist: result.data.sourcelist});
    }

    onRequestListFailed(msg) {
        this.setState({isLoading: false, sourcelist: []});
        Alert.alert(msg);
    }

    // 组件即将被卸载时
    componentWillUnmount() {
        Util.currentBrand = null;
        Util.currentSeries = null;
        Util.currentModel = null;
    }

    // 组件被渲染时
    render() {
        if (this.state.isLoading) {
            return (
                <View style={chjStyle.mainContainer}>
                    <ModuleCommonHeader title='基本信息(01)' clickedLeft={this.clickedBack.bind(this)} leftText='返回'
                                        clickedRight={this.clickedNew.bind(this)} rightText='保存'/>
                    <ActivityIndicator
                        animating={true}
                        style={{alignItems: 'center', justifyContent: 'center', height: chjStyle.height}}
                        size="large"/>
                </View>
            );
        }
        console.log('BaseInfo render    ' + JSON.stringify(Util.selectCar.basicinfo.carmodel));
        return (
            <View style={chjStyle.mainContainer}>
                <ModuleCommonHeader title='基本信息(01)' clickedLeft={this.clickedBack.bind(this)} leftText='返回'
                                    clickedRight={this.clickedNew.bind(this)} rightText='保存'/>
                <ScrollView
                    style={chjStyle.mainList}>
                    <CommonTextItem object={Util.selectCar.basicinfo.carbrand}
                                    onClickedListener={this.onBrandClicked.bind(this)} ref='brandItem'/>
                    <CommonTextItem object={Util.selectCar.basicinfo.carseries}
                                    onClickedListener={this.onSeriesClicked.bind(this)} ref='seriesItem'/>
                    <InputTextItem object={Util.selectCar.basicinfo.carmodel}
                                   autoCapitalize='characters'
                                   onClickedListener={this.onModelClicked.bind(this)} ref='modelItem'/>
                    <InputTextItem object={Util.selectCar.basicinfo.vehiclevincode} autoCapitalize='characters'
                                   keyboardType='default' maxLength={17} minLength={17}
                                   onTextChangedListener={this.onTextChanged.bind(this)}/>
                    <InputTextItem object={Util.selectCar.basicinfo.licencenumber} autoCapitalize={'characters'}
                                   keyboardType={'default'} maxLength={7} minLength={7}
                                   onTextChangedListener={this.onTextChanged.bind(this)}/>
                    <InputTextItem object={Util.selectCar.basicinfo.enginenumber} keyboardType={'default'}
                                   maxLength={19} onTextChangedListener={this.onTextChanged.bind(this)}/>
                    <SingleSelectionTextItem object={Util.selectCar.basicinfo.vehicleorigin}
                                             onSelectedListener={this.onSelected.bind(this)}
                                             optionArray={[{name: "合资"}, {name: "进口"}, {name: "国产"}]}/>
                    <DateInputTextItem object={Util.selectCar.basicinfo.firstrecorddate} maxDate={new Date()}/>
                    <DateInputTextItem object={Util.selectCar.basicinfo.leaverecorddate} onlyYearMonth={true}
                                       maxDate={new Date()}/>
                    <SingleSelectionTextItem object={Util.selectCar.basicinfo.useproperty}
                                             onSelectedListener={this.onSelected.bind(this)}
                                             optionArray={[{name: '家庭用车', val: 0}, {name: '营运用车', val: 1}, {
                                                 name: '出租车',
                                                 val: 2
                                             }, {name: '公务用车', val: 3}, {name: '其它', val: 4}, {name: '营转非', val: 5}]}/>
                    <InputTextItem object={Util.selectCar.basicinfo.carownername} keyboardType={'default'}
                                   maxLength={19} onTextChangedListener={this.onTextChanged.bind(this)}/>
                    <InputTextItem object={Util.selectCar.basicinfo.carowneridcard} keyboardType={'default'}
                                   maxLength={18} minLength={18} onTextChangedListener={this.onTextChanged.bind(this)}/>
                    <CommonTextItem object={Util.selectCar.basicinfo.carterritorial}
                                    onClickedListener={this.onProvinceClicked.bind(this)} ref='cityItem'/>
                    <InputTextItem object={Util.selectCar.basicinfo.presaleprice} autoCapitalize={'characters'}
                                   keyboardType={'numeric'} onTextChangedListener={this.onTextChanged.bind(this)}/>
                    <CommonTextItem object={Util.selectCar.basicinfo.sid}
                                    onClickedListener={this.onCarSourceItemClicked.bind(this)}
                                    valueRenderer={this.sourceItemValueRenderer.bind(this)} ref='csItem'/>
                    <CommonTextItem object={Util.selectCar.basicinfo.areaid}
                                    onClickedListener={this.onShopSourceItemClicked.bind(this)}
                                    valueRenderer={this.shopSourceItemValueRenderer.bind(this)} ref='ssItem'/>

                    <DateInputTextItem object={Util.selectCar.basicinfo.yearlyinspectiondate} onlyYearMonth={true}/>
                    <DateInputTextItem object={Util.selectCar.basicinfo.proofoftraveltaxdate} onlyYearMonth={true}
                                       onDatePickedListener={this.onProofDatePicked.bind(this)} ref='inputproof'/>
                    <DateInputTextItem object={Util.selectCar.basicinfo.stronginsurancedate} onlyYearMonth={true}
                                       onDatePickedListener={this.onStrongDatePicked.bind(this)} ref='inputstrong'/>

                    <SwitchTextItem object={Util.selectCar.basicinfo.purchasetaxcertificate}
                                    onValueChangedListener={this.onSelected.bind(this)} onValue='有' offValue='无'/>
                    <SwitchTextItem object={Util.selectCar.basicinfo.licenseplate}
                                    onValueChangedListener={this.onSelected.bind(this)} onValue='有' offValue='无'/>
                    <SwitchTextItem object={Util.selectCar.basicinfo.drivinglicense}
                                    onValueChangedListener={this.onSelected.bind(this)} onValue='有' offValue='无'/>
                    <SwitchTextItem object={Util.selectCar.basicinfo.registrationcertificate}
                                    onValueChangedListener={this.onSelected.bind(this)} onValue='有' offValue='无'/>
                    <SwitchTextItem object={Util.selectCar.basicinfo.insurancepolicy}
                                    onValueChangedListener={this.onSelected.bind(this)} onValue='有' offValue='无'/>
                    <SwitchTextItem object={Util.selectCar.basicinfo.endorsement}
                                    onValueChangedListener={this.onSelected.bind(this)} onValue='有' offValue='无'/>
                    <SwitchTextItem object={Util.selectCar.basicinfo.caruseInstructions}
                                    onValueChangedListener={this.onSelected.bind(this)} onValue='有' offValue='无'/>

                    {
                        this.renderDealItem()
                    }

                    <InputTextItem object={Util.selectCar.basicinfo.transfertimes} autoCapitalize={'characters'}
                                   keyboardType={'numeric'} maxLength={19}
                                   onTextChangedListener={this.onTextChanged.bind(this)}/>
                    <CommonTextItem object={Util.selectCar.basicinfo.legalvoucher}
                                    onClickedListener={this.onOtherClicked.bind(this)} ref='otherItem'/>
                </ScrollView>
                <NextButton onClickedListener={() => this.clickedNew()}/>
            </View>
        );
    }

    renderDealItem() {
        const items = [];
        if (this.state.tradeType === '个人') {
            items.push(<SingleSelectionTextItem object={Util.selectCar.basicinfo.tradeinfotype}
                                                onSelectedListener={this.onTradeTypeSelected.bind(this)}
                                                optionArray={[{name: '个人', val: 0}, {name: '企业', val: 1}]}/>);

            Util.selectCar.basicinfo.tradesubject.name = '客户姓名';
            items.push(<InputTextItem object={Util.selectCar.basicinfo.tradesubject} autoCapitalize={'characters'}
                                      keyboardType={'default'} maxLength={19}/>)
            Util.selectCar.basicinfo.tradesubcode.name = '证件号码';
            items.push(<InputTextItem object={Util.selectCar.basicinfo.tradesubcode} autoCapitalize={'characters'}
                                      keyboardType={'default'} maxLength={18}/>)
            Util.selectCar.basicinfo.tradecontacts.name = '证件类型';
            items.push(<SingleSelectionTextItem object={Util.selectCar.basicinfo.tradecontacts}
                                                optionArray={[{name: "二代身份证"}, {name: "护照"}, {name: "军官证"}]}/>);
            items.push(<InputTextItem object={Util.selectCar.basicinfo.tradecontactnumber} autoCapitalize={'characters'}
                                      keyboardType={'numeric'} maxLength={11} minLength={11}/>);
            items.push(<InputTextItem object={Util.selectCar.basicinfo.tradecontactaddress}
                                      autoCapitalize={'characters'} keyboardType={'default'} maxLength={20}/>);
        }
        else if (this.state.tradeType === '企业') {
            items.push(<SingleSelectionTextItem object={Util.selectCar.basicinfo.tradeinfotype}
                                                onSelectedListener={this.onTradeTypeSelected.bind(this)}
                                                optionArray={[{name: '个人', val: 0}, {name: '企业', val: 1}]}/>);

            Util.selectCar.basicinfo.tradesubject.name = '公司名称';
            items.push(<InputTextItem object={Util.selectCar.basicinfo.tradesubject} autoCapitalize={'characters'}
                                      keyboardType={'default'} maxLength={19}/>)
            Util.selectCar.basicinfo.tradesubcode.name = '组织机构代码';
            items.push(<InputTextItem object={Util.selectCar.basicinfo.tradesubcode} autoCapitalize={'characters'}
                                      keyboardType={'default'} maxLength={18}/>)
            Util.selectCar.basicinfo.tradecontacts.name = '联系人姓名';
            items.push(<InputTextItem object={Util.selectCar.basicinfo.tradecontacts} autoCapitalize={'characters'}
                                      keyboardType={'default'} maxLength={18}/>);
            items.push(<InputTextItem object={Util.selectCar.basicinfo.tradecontactnumber} autoCapitalize={'characters'}
                                      keyboardType={'numeric'} maxLength={11}/>);
            items.push(<InputTextItem object={Util.selectCar.basicinfo.tradecontactaddress}
                                      autoCapitalize={'characters'} keyboardType={'default'} maxLength={20}/>);
        }
        return items;
    }

    onTradeTypeSelected(value) {
        this.setState({
            tradeType: value
        });
    }

    onProofDatePicked(year, month, day) {
        this.refs.inputstrong.setDate(year, month, day);
    }

    onStrongDatePicked(year, month, day) {
        this.refs.inputproof.setDate(year, month, day);
    }

    onTextChanged(value) {

    }

    onBrandClicked() {
        Actions.CarBrandSelection(
            {
                name: 'CarBrandSelection',
                component: CarBrandSelection,
                onSelectedBrandListener: this.onBrandSelected.bind(this),
                onSelectedSeriesListener: this.onSeriesSelected.bind(this),
                onSelectedModelListener: this.onModelSelected.bind(this),
            }
        );
    }

    onBrandSelected(value) {
        Util.currentBrand = value;
        this.refs.brandItem.props.object.value = value;
        this.refs.brandItem.setState(
            {v: value}
        );
    }

    onSeriesSelected(value) {
        Util.currentSeries = value;
        this.refs.seriesItem.props.object.value = value;
        this.refs.seriesItem.setState(
            {v: value}
        );
    }

    onModelSelected(value) {
        Util.currentModel = value;
        this.refs.modelItem.props.object.value = value;
        this.refs.modelItem.setState(
            {v: value}
        );
        //
        // Util.selectCar.needSave = true;
    }

    onSeriesClicked(value) {
        if (!Util.currentBrand) {
            Alert.alert('请先选择车辆品牌');
            return;
        }
        Actions.CarSeriesSelection(
            {
                name: 'CarSeriesSelection',
                component: CarSeriesSelection,
                onSelectedListener: this.onSeriesSelected2.bind(this),
                data: Util.carSeries[Util.currentBrand]
            }
        );
    }

    onSeriesSelected2(value) {
        this.onSeriesSelected(value);
        Actions.CarModelSelection(
            {
                type: ActionConst.REPLACE,
                name: 'CarModelSelection',
                component: CarModelSelection,
                onSelectedListener: this.onModelSelected2.bind(this),
                data: Util.carModels[value]
            }
        );
    }

    onModelSelected2(value) {
        this.onModelSelected(value);
        Actions.pop();
    }

    onModelClicked() {
        if (!Util.currentSeries) {
            Alert.alert('请先选择车辆系列');
            return;
        }
        Actions.CarModelSelection(
            {
                name: 'CarModelSelection',
                component: CarModelSelection,
                onSelectedListener: this.onModelSelected2.bind(this),
                data: Util.carModels[Util.currentSeries]
            }
        );
    }

// ------------------------ 车辆来源 -----------------------------
    sourceItemValueRenderer(sid) {
        if (this.state.sourcelist) {
            for (let i = 0; i < this.state.sourcelist.length; i++) {
                const data = this.state.sourcelist[i];
                if (data.sid === sid) {
                    return data.source;
                }
            }
        }
        else if (sid) {
            return sid;
        }
        return '未设置';
    }

    _setDialog(array, select) {
        Actions.dialog({
            array,
            select,
        });
    }

    onCarSourceItemClicked() {
        this._setDialog([
            {name: '个人', value: 1},
            {name: '商家', value: 2},
        ], value => {
            this._enterCarSource(value);
        });
    }


    _enterCarSource(info) {
        const {value} = info;
        Actions.CarSourceSelector(
            {
                originType: value,
                onSelectedListener: (d) => this.onCarSourceSelected(d)
            }
        );
    }

    _shopSourceSelected(info) {
        const value = info.value;
        this.refs.ssItem.props.object.value = value;
        this.refs.ssItem.setState({
            v: this.shopSourceItemValueRenderer(value)
        });
    }


    onCarSourceSelected(value) {
        this.refs.csItem.props.object.value = value.sid;
        this.refs.csItem.setState({
            v: value.source
        });
    }

    onShopSourceItemClicked() {
        if (!this.state.shopSourcelist)
            return;
        const array = [];
        for (let i = 0; i < this.state.shopSourcelist.length; i++) {
            const shopSource = this.state.shopSourcelist[i];
            array.push({name: shopSource.areaname, value: shopSource.areaid});
        }
        this._setDialog(array, value => {
            this._shopSourceSelected(value);
        });
    }

    shopSourceItemValueRenderer(data) {
        if (this.state.shopSourcelist) {
            const areaid = data;
            for (let i = 0; i < this.state.shopSourcelist.length; i++) {
                const data = this.state.shopSourcelist[i];
                if (data.areaid === areaid) {
                    return data.areaname;
                }
            }
        }
        else if (data) {
            return data;
        }
        return '未设置';
    }

// ------------------------ 选择城市 ---------------------------
    onProvinceClicked() {
        Actions.CommonListSelection({
            title: 'CommonListSelection',
            component: CommonListSelection,
            name: '选择省份',
            data: cityJson,
            onSelectedListener: (prov) => this.onProvinceSelected(prov)
        });
    }

    onProvinceSelected(prov) {
        console.log('BaseInfo onProvinceSelected ' + prov);
        // 选择城市
        Actions.CommonListSelection({
            title: 'CommonListSelection2',
            component: CommonListSelection,
            name: '选择城市',
            data: prov.city,
            onSelectedListener: (city) => this.onCitySelected(prov.name, city.name)
        });
    }

    onCitySelected(prov, city) {
        if (prov.indexOf(city) !== -1) {
            city = '';
        }

        this.refs.cityItem.props.object.value = prov + city;
        this.refs.cityItem.setState({
            v: prov + city
        });
        Actions.BaseInfo({type: ActionConst.PUSH_OR_POP});
    }

// ------------------------ 其他法定凭证 ------------------------------
    onOtherClicked() {
        Actions.CommonListSelection(
            {
                title: '其他法定凭证',
                name: 'CommonMultiListSelection',
                component: CommonMultiListSelection,
                optionArray: ["购车发票", "保养手册", "进口关单", "商检单"],
                onResultListener: this.onOptionResult.bind(this),
                defaultValueArray: this.refs.otherItem.props.object.value
            }
        );
    }

    onOptionResult(resultArray) {
        this.refs.otherItem.props.object.value = resultArray;
        this.refs.otherItem.setState({
            v: resultArray.toString()
        });
    }

// --------------------------------------------------------------------

    onSelected(value) {

    }

    clickedBack() {
        Util.saveData('cars', Util.selectCar);
        Util.selectCar = null;
        DeviceEventEmitter.emit('update', ' ');
        Actions.pop();
    }

    clickedNew() {
        console.log('BaseInfo clickedNew    ' + JSON.stringify(Util.selectCar));
        Util.saveData('cars', Util.selectCar);
        Actions.CarConfig({
            name: 'CarConfig',
        });
    }
}

const mapStateToProps = (state) => {
    return {};
};

const mapDispatchToProps = (dispatch) => {
    return {};
};
export default connect(mapStateToProps, mapDispatchToProps)(BaseInfo);
